<template>
  <div class="subject-container">
    <div class="table-operations">
      <a-space>
        <a-input-search
          v-model:value="searchText"
          placeholder="搜索科目"
          style="width: 200px"
          @search="onSearch"
        />
        <a-button type="primary" @click="showModal()">
          <template #icon><plus-outlined /></template>
          添加科目
        </a-button>
      </a-space>
    </div>

    <a-table :columns="columns" :data-source="filteredData" :loading="loading" row-key="id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="showModal(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个科目吗？"
              @confirm="handleDelete(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:visible="modalVisible"
      :title="currentRecord ? '编辑科目' : '添加科目'"
      @ok="handleOk"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="科目名称" name="name">
          <a-input v-model:value="formState.name" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import request from '../../utils/request'

const API_URL = '/subjects'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: '80px'
  },
  {
    title: '科目名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '操作',
    key: 'action',
    width: '150px'
  },
]

const data = ref([])
const loading = ref(false)
const searchText = ref('')
const modalVisible = ref(false)
const currentRecord = ref(null)
const formRef = ref()

const formState = reactive({
  name: ''
})

const rules = {
  name: [{ required: true, message: '请输入科目名称!' }],
}

// 根据搜索文本过滤数据
const filteredData = computed(() => {
  if (!searchText.value) {
    return data.value
  }
  return data.value.filter(item => 
    item.name.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 搜索处理
const onSearch = (value) => {
  searchText.value = value
}

// 显示模态框
const showModal = (record = null) => {
  currentRecord.value = record
  if (record) {
    Object.assign(formState, record)
  } else {
    Object.assign(formState, {
      name: ''
    })
  }
  modalVisible.value = true
}

// 处理表单提交
const handleOk = () => {
  formRef.value.validate().then(() => {
    if (currentRecord.value) {
      // 更新科目
      updateSubject(currentRecord.value.id, formState)
    } else {
      // 创建科目
      createSubject(formState)
    }
  }).catch(error => {
    console.error('Validation failed:', error)
  })
}

// 处理删除
const handleDelete = (id) => {
  deleteSubject(id)
}

// 获取所有科目
const fetchSubjects = async () => {
  loading.value = true
  try {
    const result = await request.get(API_URL)
    data.value = result
  } catch (error) {
    console.error('Error fetching subjects:', error)
    message.error('获取科目列表失败')
  } finally {
    loading.value = false
  }
}

// 创建科目
const createSubject = async (subjectData) => {
  loading.value = true
  try {
    const result = await request.post(API_URL, subjectData)
    data.value.push(result)
    message.success('科目添加成功')
    modalVisible.value = false
  } catch (error) {
    console.error('Error creating subject:', error)
    message.error('科目添加失败')
  } finally {
    loading.value = false
  }
}

// 更新科目
const updateSubject = async (id, subjectData) => {
  loading.value = true
  try {
    const result = await request.put(`${API_URL}/${id}`, subjectData)
    const index = data.value.findIndex(item => item.id === id)
    if (index !== -1) {
      data.value[index] = result
    }
    message.success('科目更新成功')
    modalVisible.value = false
  } catch (error) {
    console.error('Error updating subject:', error)
    message.error('科目更新失败')
  } finally {
    loading.value = false
  }
}

// 删除科目
const deleteSubject = async (id) => {
  loading.value = true
  try {
    await request.delete(`${API_URL}/${id}`)
    data.value = data.value.filter(item => item.id !== id)
    message.success('科目删除成功')
  } catch (error) {
    console.error('Error deleting subject:', error)
    message.error('科目删除失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSubjects()
})
</script>

<style scoped>
.subject-container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
}
</style>